package com.wenye.Util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtil {

    private static final String SIGN = "!5$#%*gsakldjhfladksfgjhkasdghjkleahd";

    //生成token
    public static String getToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 30);

        // 创建JWT builder
        JWTCreator.Builder builder = JWT.create();

        // payload
        // 将map中的信息导入payload
        map.forEach((key, value) -> {
            builder.withClaim(key, value);
        });

        // 设置过期时间和签名
        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SIGN));

        return token;
    }

    // 验证token 并返回token信息
    public static DecodedJWT Verify(String token) {
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }
}